package com.pm.business.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.pm.business.domain.*;
import com.pm.business.service.ICurrentProjectAwardService;
import com.pm.business.service.IProjectPersonService;
import com.pm.business.service.ISysFileInfoService;
import com.pm.common.core.domain.entity.SysDictData;
import com.pm.common.utils.DictUtils;
import com.pm.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.enums.BusinessType;
import com.pm.business.service.ICurrentProjectService;
import com.pm.common.utils.poi.ExcelUtil;
import com.pm.common.core.page.TableDataInfo;

/**
 * 项目基本资料Controller
 * 
 * @author zxl
 * @date 2022-05-05
 */
@RestController
@RequestMapping("/business/current_project")
public class CurrentProjectController extends BaseController
{
    @Autowired
    private ICurrentProjectService currentProjectService;
    @Autowired
    private IProjectPersonService projectPersonService;
    @Autowired
    private ICurrentProjectAwardService currentProjectAwardService;
    @Autowired
    private ISysFileInfoService sysFileInfoService;

    /**
     * 查询项目基本资料列表
     */
    @GetMapping("/getPersonProject/{personId}")
    public TableDataInfo selectPersonProjectById(@PathVariable("personId")Long personId)
    {
        return getDataTable(currentProjectService.selectPersonProjectById(personId));
    }
    /**
     * 查询项目基本资料列表
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:list')")
    @GetMapping("/list")
    public TableDataInfo list(CurrentProject currentProject)
    {
        startPage();
        List<CurrentProject> list = currentProjectService.selectCurrentProjectList(currentProject);
        if(list!=null && list.size()>0) {
            List<Long> projectIds = new ArrayList<>();
            list.forEach(cp -> {
                projectIds.add(cp.getProjectId());
            });
            List<CurrentProject> numberList = currentProjectService.selectCurrentProjectAwardNumberByProjectId(projectIds);
            if (numberList != null && numberList.size() > 0) {
                Map<Long,Integer> map = new HashMap<>();
                numberList.forEach(cp -> {
                    map.put(cp.getProjectId(),cp.getAwardNumber());
                });
                list.forEach(cp -> {
                    Integer awardNumber = map.get(cp.getProjectId());
                    cp.setAwardNumber(awardNumber==null?0:awardNumber);
                });
            }

            List<CurrentProject> infoNumberList = currentProjectService.selectCurrentProjectSysFileInfoNumberByProjectId(projectIds);
            if (infoNumberList != null && infoNumberList.size() > 0) {
                Map<Long,Integer> map = new HashMap<>();
                infoNumberList.forEach(cp -> {
                    map.put(cp.getProjectId(),cp.getInfoNumber());
                });
                list.forEach(cp -> {
                    Integer infoNumber = map.get(cp.getProjectId());
                    cp.setInfoNumber(infoNumber==null?0:infoNumber);
                });
            }
        }
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('business:current_project:list')")
    @GetMapping("/appList")
    public TableDataInfo appList(CurrentProject currentProject)
    {
        //转换参数
        if(StringUtils.isNotEmpty(currentProject.getBidAmountStr()) && currentProject.getBidAmountStr().contains("-")){
            //String []bidAmountArray = currentProject.getBidAmountStr().split("-");
            //currentProject.getParams().put("beginBidAmount",bidAmountArray[0]);
            //currentProject.getParams().put("endBidAmount",bidAmountArray[1]);
            if ("0-1百万".equals(currentProject.getBidAmountStr())){
                currentProject.setStartAmount(0);
                currentProject.setEndAmount(100);
            } else if ("1-5百万".equals(currentProject.getBidAmountStr())){
                currentProject.setStartAmount(100);
                currentProject.setEndAmount(500);
            }else if ("0.5-1千万".equals(currentProject.getBidAmountStr())){
                currentProject.setStartAmount(500);
                currentProject.setEndAmount(1000);
            }else if ("1-5千万".equals(currentProject.getBidAmountStr())){
                currentProject.setStartAmount(1000);
                currentProject.setEndAmount(5000);
            }else if ("0.5-1亿".equals(currentProject.getBidAmountStr())){
                currentProject.setStartAmount(5000);
                currentProject.setEndAmount(10000);
            }
        }else  if("大于一亿".equals(currentProject.getBidAmountStr())){
            currentProject.setStartAmount(10000);
        }
        String sponsorTimeStr = currentProject.getBidedTimeStr();
        if(StringUtils.isNotEmpty(sponsorTimeStr) && sponsorTimeStr.contains("至")){
            String []dateArray = sponsorTimeStr.split("至");
            try{
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                currentProject.setBidedStartTime(sdf.parse(dateArray[0]));
                currentProject.setBidedEndTime(sdf.parse(dateArray[1]));
            }catch (Exception e){
                logger.debug(e.toString());
            }
        }

        String status = currentProject.getPersonType();
        if(StringUtils.isNotEmpty(status)&&!StringUtils.equals(status,"状态")){
            if (StringUtils.equals(status,"未竣工")){
                currentProject.setStatus(1);
            }else if (StringUtils.equals(status,"已竣工")){
                currentProject.setStatus(2);
            }
        }
        startPage();
        List<CurrentProject> list = currentProjectService.selectCurrentProjectList(currentProject);
        TableDataInfo tempResult = getDataTable(list);
        if(list!=null && list.size()>0) {
            List<Long> projectIds = new ArrayList<>();
            list.forEach(cp -> {
                projectIds.add(cp.getProjectId());
            });
            List<CurrentProject> numberList = currentProjectService.selectCurrentProjectAwardNumberByProjectId(projectIds);
            if (numberList != null && numberList.size() > 0) {
                Map<Long,Integer> map = new HashMap<>();
                numberList.forEach(cp -> {
                    map.put(cp.getProjectId(),cp.getAwardNumber());
                });
                list.forEach(cp -> {
                    Integer awardNumber = map.get(cp.getProjectId());
                    cp.setAwardNumber(awardNumber==null?0:awardNumber);
                });
            }
        }
        TableDataInfo result = getDataTable(list);
        result.setTotal(tempResult.getTotal());
        return result;
    }

    /**
     * 导出项目基本资料列表
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:export')")
    @Log(title = "项目基本资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CurrentProject currentProject)
    {
        List<CurrentProject> list = currentProjectService.selectCurrentProjectList(currentProject);
        ExcelUtil<CurrentProject> util = new ExcelUtil<CurrentProject>(CurrentProject.class);
        util.exportExcel(response, list, "项目基本资料数据");
    }

    /**
     * 获取项目基本资料详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        CurrentProject currentProject= currentProjectService.selectCurrentProjectByProjectId(projectId);
        if(currentProject!=null && currentProject.getCurrentProjectPresonMapList()!=null
                && currentProject.getCurrentProjectPresonMapList().size()>0){
            currentProject.getCurrentProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = new ArrayList<>();
                selectedPerson.add(cppm.getPersonType());
                selectedPerson.add(cppm.getPersonId()+"");
                cppm.setSelectedPerson(selectedPerson);
            });
        }
        currentProject.setTypePersonList(projectPersonService.getCascaderList());
        return AjaxResult.success(currentProject);
    }
    @PreAuthorize("@ss.hasPermi('business:current_project:query')")
    @GetMapping(value = "appInfo/{projectId}")
    public AjaxResult getAppInfo(@PathVariable("projectId") Long projectId)
    {
        CurrentProject currentProject= currentProjectService.selectCurrentProjectByProjectId(projectId);
        if(currentProject!=null && currentProject.getCurrentProjectPresonMapList()!=null
                && currentProject.getCurrentProjectPresonMapList().size()>0){
            currentProject.getCurrentProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = new ArrayList<>();
                selectedPerson.add(cppm.getPersonType());
                selectedPerson.add(cppm.getPersonId()+"");
                cppm.setSelectedPerson(selectedPerson);
            });
        }
        List<ProjectPerson>projectPersonList = new ArrayList<>();
        if(currentProject!=null && currentProject.getCurrentProjectPresonMapList()!=null
                && currentProject.getCurrentProjectPresonMapList().size()>0){

            currentProject.getCurrentProjectPresonMapList().forEach(cppm->{
                //TODO 修改点
                ProjectPerson ss = projectPersonService.selectProjectPersonByPersonId(cppm.getPersonId());
                if(ss!=null){
                    ProjectPerson pp = new ProjectPerson();
                    pp.setPersonType(DictUtils.getDictLabel("pm_person_type",cppm.getPersonType()));
                    pp.setPersonName(ss.getPersonName());
                    pp.setLocked(cppm.getLocked());
                    projectPersonList.add(pp);
                }

            });
        }
        currentProject.setProjectPersonList(projectPersonList);

        CurrentProjectAward condition = new CurrentProjectAward();
        condition.setProjectId(projectId);
        List<CurrentProjectAward> awardList = currentProjectAwardService.selectCurrentProjectAwardList(condition);
        if(awardList!=null){
            awardList.forEach(award->{
                award.setAwardGrade(DictUtils.getDictLabel("pm_award_grade",award.getAwardGrade()));
            });
        }
        currentProject.setAwardList(awardList);

        SysFileInfo sysFileInfo = new SysFileInfo();
        sysFileInfo.setProjectId(projectId);
        List<SysFileInfo> sysFileInfoList = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        currentProject.setSysFileInfoList(sysFileInfoList);

        return AjaxResult.success(currentProject);
    }

    /**
     * 新增项目基本资料
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:add')")
    @Log(title = "项目基本资料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CurrentProject currentProject)
    {
        if(currentProject!=null && currentProject.getCurrentProjectPresonMapList()!=null
                && currentProject.getCurrentProjectPresonMapList().size()>0){
            currentProject.getCurrentProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    cppm.setPersonType(selectedPerson.get(0));
                    cppm.setPersonId(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }
        return toAjax(currentProjectService.insertCurrentProject(currentProject));
    }

    /**
     * 修改项目基本资料
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:edit')")
    @Log(title = "项目基本资料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CurrentProject currentProject)
    {
        if(currentProject!=null && currentProject.getCurrentProjectPresonMapList()!=null
                && currentProject.getCurrentProjectPresonMapList().size()>0){
            currentProject.getCurrentProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    cppm.setPersonType(selectedPerson.get(0));
                    cppm.setPersonId(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }
        return toAjax(currentProjectService.updateCurrentProject(currentProject));
    }

    /**
     * 删除项目基本资料
     */
    @PreAuthorize("@ss.hasPermi('business:current_project:remove')")
    @Log(title = "项目基本资料", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds)
    {
        return toAjax(currentProjectService.deleteCurrentProjectByProjectIds(projectIds));
    }
}
